<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/10
 * Time: 16:22
 */

namespace osc\admin\controller;

use think\Controller;
use think\Db;

class EndRemind extends Controller
{

    /**
     * 合约到期提醒接口
     * @return string
     */
    public function remind(){

        $get_token = $this->request->param('token');

        if($get_token !== 'dd88ca22fae7632'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //明天的时间
        $tomorrow = date("Y-m-d",strtotime("+1 day"));

        $b1 = Db::name('contract_b1')->where("end_day",$tomorrow)->where('con_state',0)->field('id,username')->select();
        $b2 = Db::name('contract_b2')->where("end_day",$tomorrow)->where('con_state',0)->field('id,username')->select();

        $data = array_merge($b1,$b2);

        if(!$data){ return '没有合约，请求时间为：'.date('Y-m-d H:i:s',time());}
        //循环调用短信模版发送到期提醒
        foreach($data as $key=>$value){

            $r= osc_service('common','SmsDemo')->remind_contract($value['username']);

        }

        return '合约到期提醒请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($data);

    }

    /**
     * 超过三天直接结束合约的操作
     * @return string
     * @throws \think\Exception
     */
    public function end_day(){
        $get_token = $this->request->param('token');

        if($get_token !== 'sad12314544'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //三天前的时间
        $tomorrow = date("Y-m-d",strtotime("-3 day"));

        $b1 = Db::query("update osc_contract_b1 set state=3 where end_day<'".$tomorrow."' and state <>3 ");

        $b2 = Db::query("update osc_contract_b2 set state=3 where end_day<'".$tomorrow."' and state <>3 ");
        $zong = count($b1)+count($b2);
        return '超过三天结束合约请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.$zong;

    }


    /**
     * 未上传买入凭证三天后进行扣分操作
     * @return string
     */
    public function credit_score(){
        $get_token = $this->request->param('token');

        if($get_token !== 'a231asd12345'){
            return '请求错误';
        }
        //三天前的时间
        $tomorrow = date("Y-m-d",strtotime("-3 day"));

        $b1 = Db::name('contract_b1')->where("end_day",$tomorrow)->where('buy_state <> 1')->field('id,username,info_id')->select();
        $b2 = Db::name('contract_b2')->where("end_day",$tomorrow)->where('buy_state <> 1')->field('id,username,info_id')->select();

        $data = array_merge($b1,$b2);

        if(!$data){ return '没有需要扣分的合约';}

        /*echo'<pre>';print_r($tomorrow);
        echo'<pre>';print_r($data);exit;*/

        $repulse['num']              = 5;
        $repulse['operator']         = '系统脚本';
        $repulse['level']            = 5;
        $repulse['desc']             = '买入凭证未上传';

        //循环进行扣除信用分
        foreach($data as $value){
            // 启动事务
            Db::startTrans();
            try {
                $repulse['contract_id']      = $value['id'];
                $repulse['type']             = $value['info_id'];
                $repulse['contract_state']   = 2;
                $repulse['username']         = $value['username'];

                $contract_repulse = Db::name('contract_repulse')->insert($repulse);

                $credit_score = Db::name('member')->where('username',$value['username'])->setDec('credit_score',$repulse['num']);

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }

        }

        return '请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，扣合约数为：'.count($data);

    }

    /**
     * 每天按比例释放会员吉豆为元宝
     * @return string
     * @throws \think\Exception
     */
    public function jilin_release(){
        $get_token = $this->request->param('token');

        if($get_token !== 'qweqzsd123we'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        $time = date('Y-m-d',time());
        $holiday = Db::name('holiday')->where('date_dt',$time)->find();

        if($holiday){
            return '当天是节假日请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //查询所有吉豆不为0的用户
        $user_info = Db::name('member')->where('jilt<>0 and user_state<>0')->field('username,jilt,user_state')->select();

        $this->jilin_handle($user_info);

        $map = [
            'dt'			=> date('Y-m-d',time()),
            'bao'			=> Db::name('member')->sum('bao'),
            'jilt'			=> Db::name('member')->sum('jilt'),
            'jilin_bean'	=> Db::name('member')->sum('jilin_bean')
        ];

        Db::name('integral')->insert($map);

        return '吉豆每日释放成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($user_info);

    }

    /**
     * 操作执行
     * @param $data
     * @return bool
     */
    function jilin_handle($data){

        $rollback = [];
        foreach($data as $key=>$value){
            //获取等级利率
            $rate = get_user_state_rate($value['user_state']);

            if($value['jilt'] == 0.01){
                $rate = 1;
            }

            // 开启事务
            Db::startTrans();
            try{

                $map = [
                    'username'          => $value['username'],
                    'rate'              => $rate,
                    'num'               => round($rate*$value['jilt'],2),
                    'type'              => 2,
                    'create_time'       => time(),
                ];

                //扣除吉豆增加元宝录入释放记录
                Db::name('member')->where('username',$value['username'])->setDec('jilt',$map['num']);
                Db::name('member')->where('username',$value['username'])->setInc('jilin_bean',$map['num']);

                Db::name('release')->insert($map);

                // 更新成功 提交事务
                Db::commit();

            }catch (\Exception $e){
                // 更新失败 回滚事务
                Db::rollback();

                $rollback[$key] = [
                    'username'      => $value['username'],
                    'jilt'          => $value['jilt'],
                    'user_state'    => $value['user_state']
                ];
            }
        }

        if($rollback){
            $this->jilin_handle($rollback);
        }

        return true;
    }


    /**
     * 可用额度每日释放
     * @return string
     */
    public function can_release(){

        $time = date('Y-m-d',time());

        $rew = Db::query("update osc_member a,osc_delivery b set  a. can_quota = a.stay_quota * 0.1 where a.username = b.username and b.vou_date = '".$time."' and b.state = 3");

        if($rew){
            return '可用额度释放成功，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        return '可用额度释放失败，请求时间为：'.date('Y-m-d H:i:s',time());
    }



}